import React, { useState, useEffect } from "react";
import { Image, Swiper, SwiperItem } from "@tarojs/components";
import Taro from "@tarojs/taro";
import classNames from "classnames";

import * as api from "./api";
import "./index.scss";

interface AdItem {
  id: number; // int # 学校id
  thumbnail: string; // char # 学校logo
  name: string; // char # 名称
  url: string; // char # 描述
}

interface Iprops {
  /**
   * 广告类别
   */
  label: string;
  interval?: number;
  className?: string;
  refreshAdFlag?:boolean //广告何时刷新的 falg
}

const Index: React.FC<Iprops> = (props: Iprops) => {
  const [loading, setLoading] = useState(false);
  const [data, setData] = useState<AdItem[]>([]);

  useEffect(() => {
    console.log('refreshAdFlag------>>',props.refreshAdFlag)
    const getMajorData = async () => {
      try {
        const { result, status } = await api.adsense_advertisement_search({
          search_info: JSON.stringify({
            label: props.label,
          }),
        });
        status === "ok" && setData(result.data_list);
      } catch (err) {
        console.log("err--------->>>", err);
      } finally {
        setLoading(false);
      }
    };
    getMajorData();
  }, [props.refreshAdFlag]);

  const onSwitchPage = (url: string) => {
    const parseUrl = url.split("&");
    console.log(parseUrl);
    if (parseUrl[0] === "type=http") {
      Taro.navigateTo({
        url: `/pages/webview/index?src=${parseUrl[1].split("=")[1]}`,
      });
    }

    if (parseUrl[0] === "type=goods") {
      Taro.navigateTo({
        url: `/pages/goodsDetail/index?goods_id=${parseUrl[1].split("=")[1]}`,
      });
    }
  };

  return (
    <Swiper
      className={classNames("ad", props.className && props.className)}
      indicatorColor="#999"
      indicatorActiveColor="#333"
      circular
      indicatorDots={false}
      autoplay
      interval={props.interval || 5000}
    >
      {data.map((item) => (
        <SwiperItem key={item.id} onClick={() => onSwitchPage(item.url)}>
          <Image src={item.thumbnail} />
        </SwiperItem>
      ))}
    </Swiper>
  );
};

export default Index;
